package com.leef.oauth.data.api;

import com.leef.oauth.common.AppConfigs;
import com.leef.oauth.data.api.ouath.OauthService;
import com.leef.oauth.data.pojo.Token;
import com.leef.oauth.util.SharePrefsUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.functions.Function;
import retrofit2.Response;
import timber.log.Timber;

/**
 * Created by IWALL on 2017/3/14.
 * Rest API Center
 */

public class RestApi {
    private static final RestApi ourInstance = new RestApi();

    public static RestApi getInstance() {
        return ourInstance;
    }

    private RestApi() {
    }

    private OauthService oauthService = null;
    private ApiService apiService = null;

    public OauthService getOauthService() {
        if (oauthService == null) {
            oauthService = RetrofitApi.createService(OauthService.class);
        }
        return oauthService;
    }

    public ApiService getApiService() {
        if (apiService == null) {
            apiService = RetrofitApi.createService(ApiService.class);
        }
        return apiService;
    }

    public static <T> FlowableTransformer<Response<T>, Response<T>> checkTokenIsExpired() {
        return upstream -> upstream.flatMap(response -> {
            if (response.isSuccessful() || response.code() != 401) {
                return Flowable.just(response);
            }
            return Flowable.error(new Exception("Unauthorized"));
        });
    }

    public static <R> Function<Throwable, Flowable<Response<R>>> refreshToken(Flowable<Response<R>> observable) {
        return throwable -> {
            Timber.d(throwable, throwable.getMessage());
            //  1.从本地存储获取 refresh_token
            String refresh_token = SharePrefsUtils.getString(AppConfigs.REFRESH_TOKEN, "");
            //  2.构建刷新 token 的接口参数
//            Map<String, String> map = new HashMap<>();
//            map.put("client_id", "dd901a9812924c45b8bd28f3f1a3b0bb");
//            map.put("client_secret", "DeAKvWGCcZ554eD5pbLrpk9lH9BP8P2q");
//            map.put("grant_type", "refresh_token");
//            map.put("refresh_token", refresh_token);
            Map<String, String> map = new HashMap<>();
            map.put("client_id", "mobile-client");
            map.put("client_secret", "mobile");
            map.put("grant_type", "refresh_token");
            map.put("refresh_token", refresh_token);
            //  3.调用 refresh_token 接口,保存新的 access_token 和 refresh_token
            return RestApi.getInstance().getOauthService().refreshToken(map)
                    .flatMap(response -> {
                        Token token = response.body();
                        if (token != null) {
                            SharePrefsUtils.setValue(AppConfigs.ACCESS_TOKEN,
                                    response.body().getAccessToken());
                            SharePrefsUtils.setValue(AppConfigs.REFRESH_TOKEN,
                                    response.body().getRefreshToken());
                            //  update interceptor's token
                            RetrofitApi.updateToken(token.getAccessToken());
                        }
                        return observable;
                    });
        };
    }

}
